package com.ryi.life.service;

import com.ryi.life.entity.User;
import com.ryi.life.mapper.UserMapper;
import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.subject.PrincipalCollection;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

/**
 * 用户的service
 * Created by heshun on 15-12-30.
 */
@Service("userService")
public class UserServiceImpl implements UserService {

    @Autowired
    private UserMapper userMapper;

    /**
     * shiro的验证
     *
     * @param principalCollection
     * @param name
     * @return
     */
    public AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken principalCollection, String name) {
        UsernamePasswordToken token = (UsernamePasswordToken) principalCollection;
        // 通过表单接收的用户名
        String loginName = token.getUsername();

        if (StringUtils.isEmpty(loginName)) {
            throw new UnknownAccountException();
        }

        // 通过登录名称查询用户信息
        User user = userMapper.findByUserName(loginName);
        if (user != null) {
            return new SimpleAuthenticationInfo(user, user.getPassword(), name);
        }
        throw new UnknownAccountException();
    }

    @Override
    public AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
        User principal = (User) principalCollection.getPrimaryPrincipal();
        if (principal != null) {
            SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();
            // 获取用户角色
            info.addStringPermission("index:index");
//            info.addStringPermission("index:go");
            return info;
        }

        return null;
    }
}

